<?php

namespace App\Service\OpenShop\SiteLocation;

use App\Enums\WorkOrder\OrderEnum;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\ConfigModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\SmsService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Message\BaseMessageService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Rms\ShopService;
use App\Service\WorkOrder\Manager\ManagerService;
use App\Support\FeishuMsgSupport;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;


class SendFsService extends BaseMessageService
{

    private ?object $placeholderInfo = null;

    public function __construct(string $orderNo = '', int $source = OpenShopSiteLocationModel::SOURCE_PLACEHOLDER)
    {
        switch ($source) {
            case OpenShopSiteLocationModel::SOURCE_PLACEHOLDER:
                $this->placeholderInfo = OpenShopSiteLocationModel::query()
                                                                  ->where('source',
                                                                      OpenShopSiteLocationModel::SOURCE_PLACEHOLDER)
                                                                  ->where('orderNo', $orderNo)
                                                                  ->first();
                break;
            default:
        }
        parent::__construct($orderNo);
    }

    public function sendAuditHandleNotify(array $userIds)
    {
        $template     = $this->getTemplateFile('OpenShop/feishu/notifyTemplate/placeholderResultNotify.json');
        $templateJson = json_decode(vsprintf($template, [
            $this->getJumpUrl()
        ]), true);
        $fsIds        = $this->getUserFsIds($userIds);
        MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_OPEN_SHOP, $fsIds);
    }

    public function sendAuditNotify(array $userIds)
    {
        $template     = $this->getTemplateFile('OpenShop/feishu/notifyTemplate/placeholderNotify.json');
        $templateJson = json_decode(vsprintf($template, [
            $this->getJumpUrl('audit')
        ]), true);
        $fsIds        = $this->getUserFsIds($userIds);
        MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_OPEN_SHOP, $fsIds);
    }


    private function getUrl()
    {
        $path  = "workOrder/manage/info/{$this->workOrderApplyMainModel->workOrderNo}?isMainModule=1";
        $appid = config("feishu." . UserPermissionAuth::MODULE_WORK_ORDER . ".appID");

        return "https://applink.feishu.cn/client/web_app/open?appId={$appid}&path=$path";
    }

    public function getTemplateFile(string $filePath)
    {
        $template = file_get_contents(resource_path($filePath));
        $result   = array();
        preg_match_all("/\{\{(.*)\}\}/U", $template, $result);


        $params        = [];
        $paramsBracket = [];
        foreach ($result[1] as $value) {
            $params[$value]                      = $this->$value;
            $paramsBracket['{{' . $value . '}}'] = $this->$value;
        }
        $paramsKeys   = array_keys($paramsBracket);
        $paramsValues = array_values($paramsBracket);

        $template = str_replace($paramsKeys, $paramsValues, $template);

        return $template;
    }

    public function __get($paramName)
    {
        if (method_exists($this, 'get' . $paramName)) {
            return call_user_func([$this, 'get' . $paramName]);
        } else {
            dd('方法:' . 'get' . $paramName . '不存在');
        }
    }

    protected ?object $lastExamineInfo;

    public function getLastExamineInfo()
    {
        if (empty($this->lastExamineInfo)) {
            $this->lastExamineInfo = OpenShopSiteLocationExamineLogModel::query()
                                                                        ->where("source",
                                                                            OpenShopSiteLocationModel::SOURCE_PLACEHOLDER)
                                                                        ->where('orderNo', $this->orderNo)
                                                                        ->orderBy('id', 'desc')
                                                                        ->first();
        }
        return $this->lastExamineInfo;
    }

    /**
     * 标题颜色
     *
     * @return string
     */
    public function getAuditTitleColor(): string
    {
        $lastExamine = $this->getLastExamineInfo();

        if ($lastExamine->status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {
            return 'green';
        } else {
            return 'red';
        }
    }

    /**
     * 申请人
     *
     * @return string
     */
    public function getApplyFor(): string
    {
        return $this->placeholderInfo->developConsultantName;
    }

    /**
     * 预占点位地址
     *
     * @return string
     */
    public function getPlaceholderAddress(): string
    {
        return $this->placeholderInfo->siteAddress;
    }


    /**
     * 获取预占点位的时间段
     *
     * @return string
     */
    public function getPlaceholderTimeExpired(): string
    {
        return date('Y-m-d', $this->placeholderInfo->placeholderTime);
    }

    /**
     * 附近门店距离
     *
     * @return string
     */
    public function getNearShopDistance(): string
    {
        return bccomp($this->placeholderInfo->nearbyRange, '0.00') == 0 ? '-' : $this->placeholderInfo->nearbyRange;
    }

    /**
     * 附近门店名字
     *
     * @return string
     */
    public function getNearShopName(): string
    {
        if ($this->placeholderInfo->nearbyShopCode == 0) {
            return '-';
        }
        return ShopService::getShopNameByCode($this->placeholderInfo->nearbyShopCode) ?? '';
    }

    /**
     * 处理人名字
     *
     * @return string
     */
    public function getDealUsername(): string
    {
        $body     = RmsUserService::getRmsUserInfoByUserIds($this->getLastExamineInfo()->createdByUid)['data'] ?? [];
        $username = '';
        if (!empty($body) && !empty($body[0])) {
            $username = $body[0]['username'] ?? '';
        }
        return $username;
    }

    public function getUserFsIds(array $userIdArr)
    {
        $userList = RmsUserService::getRmsUserInfoByUserIds($userIdArr)['data'] ?? [];
        $fsIds    = array_column($userList, 'feishuUserId');
        return $fsIds;
    }

    /**
     * 处理角色
     *
     * @return string
     */
    public function getDealUserRole(): string
    {
        return OpenShopSiteLocationExamineLogModel::POSITION_EXAMINE_MAPPING[$this->getLastExamineInfo()->position] ?? '';
    }


    /**
     * 处理结果
     *
     * @return string
     */
    public function getDealResult(): string
    {
        return OpenShopSiteLocationExamineLogModel::STATUS_MAPPING[$this->getLastExamineInfo()->status] ?? '';
    }

    /**
     * 获取处理内容
     *
     * @return string
     */
    public function getAuditContent(): string
    {
        return $this->getLastExamineInfo()->content;
    }

    /**
     * 获取跳转 url
     *
     * @return string
     */
    public function getJumpUrl(string $type = 'examine')
    {
        $appid = ConfigModel::getFsConfigByPlatformNameOrgId('site', 0)['appId'] ?? '';

        $path = urlencode("pages/placeholder/from?orderNo={$this->orderNo}&type={$type}");

        $url = "https://applink.feishu.cn/client/mini_program/open?appId={$appid}&mode=window-semi&relaunch=true&path={$path}";

        Log::info($url);

        return $url;
    }

    public function getAuditResult()
    {
        $lastExamine = $this->getLastExamineInfo();

        if ($lastExamine->status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {
            if ($lastExamine->position == OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE) {
                return "【点位审核-通过】有新的预占点位审核通过，请注意（{$this->getShopCode()}）";
            } else {
                return "【点位审批-通过】有新的预占点位审批通过，请注意（{$this->getShopCode()}）";
            }
        } else {
            if ($lastExamine->position == OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE) {
                return "【点位审核-驳回】有新的预占点位审核驳回，请注意（{$this->getShopCode()}）";
            } else {
                return "【点位审批-驳回】有新的预占点位审批驳回，请注意（{$this->getShopCode()}）";
            }
        }

    }
}
